package com.ruoyi.exam.websocket;

import org.springframework.stereotype.Component;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;;

@Component
@ServerEndpoint(value = "/websocket/exam/ai/{sessionId}")
public class AiWebSocket {

   private static final Map<String, AiWebSocket> onLineUserMap = new ConcurrentHashMap<>();

   private Session session;

   private boolean isGenerating = false;

   @OnOpen
   public void onOpen(Session session, @PathParam("sessionId") String sessionId) {
      this.session = session;
      onLineUserMap.put(sessionId, this);
   }

   @OnMessage
   public void onMessage(Session session, @PathParam("sessionId") String sessionId, String message) {

   }

   @OnClose
   public void onClose(Session session, @PathParam("sessionId") String sessionId) {
      onLineUserMap.remove(sessionId);

   }

   public static void sendText(String sessionId, String text) throws IOException {
      AiWebSocket aiWebSocket = onLineUserMap.get(sessionId);
      if (aiWebSocket == null) {
         return;
      }
      aiWebSocket.session.getBasicRemote().sendText(text);
      aiWebSocket.isGenerating = false;
   }

   public static void waitingSend(String sessionId) {
      AiWebSocket aiWebSocket = onLineUserMap.get(sessionId);
      if (aiWebSocket == null) {
         return;
      }
      aiWebSocket.isGenerating = true;
   }

}
